﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NetMQ;
using NetMQ.Sockets;
using System.Threading;
using System.Text.RegularExpressions;

class Program
{
    private static List<string> commandHistory = new List<string>();
    private static int historyIndex = -1;
    private static string currentCommand = "";

    static void Main(string[] args)
    {
        string zmqAddress = "";
        int zmqPort = 0;
        string moduleName = "";

        // 提示用户输入 ZeroMQ 地址
        while (true)
        {
            Console.WriteLine("Please enter the ZeroMQ address (e.g., tcp://localhost):");
            zmqAddress = Console.ReadLine();
            // 自动补全 tcp:// 前缀
            if (!zmqAddress.StartsWith("tcp://"))
            {
                zmqAddress = "tcp://" + zmqAddress;
            }
            // 检查 ZeroMQ 地址的有效性
            if (IsValidZmqAddress(zmqAddress))
            {
                break;
            }
            else
            {
                Console.WriteLine("Invalid ZeroMQ address. Please try again.");
            }
        }

        // 提示用户输入模块名称
        while (true)
        {
            Console.WriteLine("Please enter the module name (e.g., chgctrl, pwrctrl):");
            moduleName = Console.ReadLine();
            if (moduleName.ToLower() == "chgctrl")
            {
                zmqPort = 6680;
                break;
            }
            else if (moduleName.ToLower() == "pwrctrl")
            {
                zmqPort = 6681;
                break;
            }
            else
            {
                Console.WriteLine("Invalid module name. Please try again.");
            }
        }

        // 创建 ZeroMQ 的请求套接字
        using (var sender = new RequestSocket($">{zmqAddress}:{zmqPort}"))
        {
            Console.WriteLine("ZeroMQ Command Line Tool");
            Console.WriteLine("Type 'exit' to quit.");
            Console.Write("\n> ");

            while (true)
            {
                ConsoleKeyInfo keyInfo = Console.ReadKey(true);
                if (keyInfo.Key == ConsoleKey.UpArrow)
                {
                    // 向上键，回滚历史命令
                    if (historyIndex > 0)
                    {
                        historyIndex--;
                        currentCommand = commandHistory[historyIndex];
                        ClearLine();
                        Console.Write("> ");
                        Console.Write(currentCommand);
                    }
                }
                else if (keyInfo.Key == ConsoleKey.DownArrow)
                {
                    // 向下键，前进历史命令
                    if (historyIndex < commandHistory.Count - 1)
                    {
                        historyIndex++;
                        currentCommand = commandHistory[historyIndex];
                        ClearLine();
                        Console.Write("> ");
                        Console.Write(currentCommand);
                    }
                    else if (historyIndex == commandHistory.Count - 1)
                    {
                        historyIndex++;
                        currentCommand = "";
                        ClearLine();
                        Console.Write("> ");
                        Console.Write(currentCommand);
                    }
                }
                else if (keyInfo.Key == ConsoleKey.Enter)
                {
                    // 发送命令
                    if (!string.IsNullOrEmpty(currentCommand))
                    {
                        if (currentCommand.ToLower() == "exit")
                        {
                            break;
                        }

                        Console.Write("\n> ");

                        try
                        {
                            sender.SendFrame(currentCommand);
                            // 接收服务器端的应答信息
                            string reply = sender.ReceiveFrameString();
                            Console.Write($"Server replied:\n{reply}");
                            commandHistory.Add(currentCommand);
                            historyIndex = commandHistory.Count;
                            currentCommand = "";
                            Console.Write("> ");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Failed to send command: {ex.Message}");
                            // 可以根据具体的异常情况添加更详细的处理逻辑
                            // 例如，重试发送、记录错误日志等
                        }
                    }
                    else 
                    {
                        Console.Write("\n> ");
                    }
                }
                else if (keyInfo.Key == ConsoleKey.Backspace)
                {
                    // 删除键，删除最后一个字符
                    if (currentCommand.Length > 0)
                    {
                        // 删除最后一个字符
                        currentCommand = currentCommand.Substring(0, currentCommand.Length - 1);
                        // 清除屏幕上的最后一个字符
                        int cursorLeft = Console.CursorLeft;
                        Console.Write("\b \b");
                    }
                }
                else
                {
                    // 正常输入字符
                    currentCommand += keyInfo.KeyChar;
                    Console.Write(keyInfo.KeyChar);
                }
            }
        }
    }

    // 检查 ZeroMQ 地址的有效性
    private static bool IsValidZmqAddress(string address)
    {
        // 使用正则表达式检查地址的格式
        string pattern = @"^(tcp|ipc|inproc|pgm)://([a-zA-Z0-9._-]+|\*|\[([a-fA-F0-9:]+)\])(:[0-9]+)?$";
        return Regex.IsMatch(address, pattern);
    }

    private static void ClearLine()
    {
        Console.SetCursorPosition(0, Console.CursorTop); // 将光标移到当前行的起始位置
        for (int i = 0; i < Console.WindowWidth; i++) // 输出空格覆盖当前行
        {
            Console.Write(" ");
        }
        Console.SetCursorPosition(0, Console.CursorTop); // 再次将光标移到当前行的起始位置
    }
}